<template>
	<view class="order-container">
		<!-- 顶部搜索栏 -->
		<view class="header">
			<view class="header-content">
				<view class="search-container">
					<view class="search-box">
						<image src="/static/image/icon_search.png" class="search-icon" mode="aspectFit"></image>
						<input type="text" placeholder="搜索订单号" v-model="searchKeyword" class="search-input"
							placeholder-class="search-placeholder" @input="onSearchInput" />
					</view>

					<view class="search-btn" @click="handleSearch">
						<text class="search-btn-text">搜索</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 分类标签 -->
		<!-- <view class="category-tabs" :style="{ marginTop: (statusBarHeight + navBarHeight) + 'px' }">
			<view v-for="(category, index) in categories" :key="index" class="category-item"
				:class="[activeCategory === index ? 'active' : '']" @click="switchCategory(index)">
				<text class="category-text">{{ category.name }}</text>
			</view>
		</view> -->

		<!-- 订单列表 -->
		<scroll-view class="order-list" scroll-y="true" @scrolltolower="loadMore">
			<!-- 加载状态 -->
			<view v-if="loading" class="loading-state">
				<text class="loading-text">加载中...</text>
			</view>

			<!-- 空状态 -->
			<view v-else-if="orderList.length === 0" class="empty-state">
				<image src="/static/image/empty_order.png" class="empty-icon" mode="aspectFit"></image>
				<text class="empty-text">暂无代付订单</text>
			</view>

			<!-- 代付订单列表 -->
			<view v-else class="order-list-container">
				<view v-for="(shareOrder, index) in orderList" :key="shareOrder.id" class="order-item">
					<!-- 订单头部 -->
					<view class="order-header">
						<view class="order-number">
							<text class="order-number-text">代付订单 {{ shareOrder.id }}</text>
						</view>
						<view class="order-status" :class="[getStatusClass(shareOrder)]">
							<text class="status-text">{{ getStatusText(shareOrder) }}</text>
						</view>
					</view>

					<!-- 代付订单信息 -->
					<view class="order-product" @click="viewOrderDetail(shareOrder)">
						<image :src="getTravelCover(shareOrder)" class="product-image" mode="aspectFill"></image>
						<view class="product-info">
							<text class="product-title">{{ getTravelName(shareOrder) }}</text>
							<text class="product-desc">购买人：{{ shareOrder.user ? shareOrder.user.nickname : '未购买' }}</text>
							<text class="order-time">{{ formatTime(shareOrder.create_time) }}</text>
						</view>
						<view class="product-price" v-if="shareOrder.travelOrder && shareOrder.travelOrder.payment_amount">
							<text class="price-symbol">¥</text>
							<text class="price-value">{{ shareOrder.travelOrder ? shareOrder.travelOrder.payment_amount : '0.00' }}</text>
						</view>
					</view>

					<!-- 代付金额信息 -->
					<view class="prepay-info" v-if="shareOrder.prepay_amount > 0">
						<text class="prepay-label">代付金额：</text>
						<text class="prepay-value">¥{{ shareOrder.prepay_amount }}</text>
					</view>

					<!-- 操作按钮 -->
					<view class="order-actions">
						<view v-if="!shareOrder.user_id && shareOrder.status !== 'cancelled'" class="action-btn primary"
							@click="openShareOrder(shareOrder)">
							<text class="action-text">分享</text>
						</view>
						<view v-if="!shareOrder.user_id && shareOrder.status !== 'cancelled'" class="action-btn secondary"
							@click="cancelShareOrder(shareOrder, '确定要取消分享吗？')">
							<text class="action-text">取消分享</text>
						</view>
						<view v-if="shareOrder.travelOrder && shareOrder.travelOrder.status === 'pending'" class="action-btn secondary"
							@click="cancelShareOrder(shareOrder, '用户已下单，暂未支付，确定要取消分享吗？')">
							<text class="action-text">取消分享</text>
						</view>
						<view v-if="shareOrder.travelOrder" class="action-btn secondary"
							@click="viewOrderDetail(shareOrder)">
							<text class="action-text">查看订单</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 加载更多 -->
			<view v-if="hasMore" class="load-more" @click="loadMore">
				<text class="load-more-text">加载更多</text>
			</view>
			<!-- <view v-else class="no-more">
				<text class="no-more-text">没有更多了</text>
			</view> -->
		</scroll-view>
	</view>
</template>

<script>
import {
	ORDER_STATUS_TEXT,
	ORDER_STATUS
} from "../../utils/enum";

export default {
	data() {
		return {
			statusBarHeight: 0,
			navBarHeight: 0,
			searchKeyword: '',
			activeCategory: 0,
			hasMore: true,
			loading: false,
			currentPage: 1,
			categories: [{
				name: '全部',
				status: ''
			},
			{
				name: '已购买',
				status: 'purchased'
			},
			{
				name: '未购买',
				status: 'unpurchased'
			}
			],
			orderList: []
		}
	},
	methods: {
		// 获取状态文本
		getStatusText(order) {
			console.log(order)
			const statusMap = {
				'pending_pricing': '待定价',
				'pending': '待付款',
				'paid': '已付款',
				'shipped': '已确认',
				'pending_receipt': '待出行',
				'completed': '已完成',
				'cancelled': '已取消',
				'refunding': '退款中',
				'refunded': '已退款'
			};

			if (!order.travelOrder) {
				const statusMap2 = {
					'pending': '待分享',
					'cancelled': '已取消'
				};
				return statusMap2[order.status] || '未知状态';
			}
			return statusMap[order.travelOrder.status] || '未知状态';
		},

		// 获取状态样式类
		getStatusClass(order) {
			const classMap = {
				'pending_pricing': 'status-pending-pricing',
				'pending': 'status-pending',
				'paid': 'status-paid',
				'shipped': 'status-shipped',
				'pending_receipt': 'status-pending-receipt',
				'completed': 'status-completed',
				'cancelled': 'status-cancelled',
				'refunding': 'status-refunding',
				'refunded': 'status-refunded'
			};

			if (!order.travelOrder) {
				return  classMap[order.status] || 'status-unknown';
			}
			return classMap[order.travelOrder.status] || 'status-unknown';
		},
		getTravelCover(shareOrder) {
			if (shareOrder.travel && shareOrder.travel.cover) {
				return shareOrder.travel.cover
			}
			return ''
		},
		// 名称
		getTravelName(shareOrder) {
			if (shareOrder.travel && shareOrder.travel.name) {
				return shareOrder.travel.name + ' - ' + this.getOrderDesc(shareOrder.travelSku.sku_spec)
			}
			return ''
		},
		// 获取订单描述
		getOrderDesc(sku_spec) {
			if (!sku_spec) {
				return ''
			}
			let _sku_spec = JSON.parse(sku_spec)
			let desc = ''
			if (_sku_spec) {
				for (let key in _sku_spec) {
					desc += `${_sku_spec[key]} `
				}
			}
			return desc
		},
		// 获取系统信息
		getSystemInfo() {
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight;

			if (uni.getMenuButtonBoundingClientRect) {
				const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
				this.navBarHeight = menuButtonInfo.height + (menuButtonInfo.top - this.statusBarHeight) * 2;
			} else {
				this.navBarHeight = 44;
			}
		},

		// 搜索输入
		onSearchInput(e) {
			this.searchKeyword = e.detail.value;
		},

		// 执行搜索
		handleSearch() {
			if (!this.searchKeyword.trim()) {
				uni.showToast({
					title: '请输入搜索关键词',
					icon: 'none'
				});
				return;
			}

			uni.showLoading({
				title: '搜索中...'
			});

			// 重置页码并搜索
			this.currentPage = 1;
			const params = {
				distributor_id: this.userInfo.id,
				pageNo: this.currentPage,
				pageSize: 10,
				travel_nameLike: this.searchKeyword.trim()
			};

			this.$api.getTravelShareOrderList(params).then(res => {
				uni.hideLoading();
				if (res && res.list) {
					this.orderList = res.list;
					this.hasMore = this.orderList.length < res.total;
				}
			}).catch(error => {
				console.error('搜索代付订单失败:', error);
			});
		},

		// 切换分类
		switchCategory(index) {
			this.activeCategory = index;

			uni.showLoading({
				title: '加载中...'
			});

			// 重置页码
			this.currentPage = 1;

			// 根据分类加载数据
			const currentStatus = this.categories[index].status;
			const params = {
				distributor_id: this.userInfo.id,
				pageNo: this.currentPage,
				pageSize: 10
			};

			// 如果有状态筛选，添加状态参数
			if (currentStatus) {
				params.status = currentStatus;
			}

			this.$api.getTravelShareOrderList(params).then(res => {
				uni.hideLoading();
				if (res && res.list) {
					this.orderList = res.list;
					this.hasMore = this.orderList.length < res.total;
				}
			}).catch(error => {
				console.error('获取代付订单列表失败:', error);
			});
		},

		// 查看代付订单详情
		viewOrderDetail(shareOrder) {
			if (shareOrder.user_id) {
				// 如果已购买，跳转到订单详情
				uni.navigateTo({
					url: `/pages/travelOrder/detail?id=${shareOrder.travelOrder.id}&shareOrderId=${shareOrder.id}`
				});
			}
		},
		cancelShareOrder(shareOrder, content) {
			// 对话确认框
			uni.showModal({
				title: '取消分享',
				content,
				success: (res) => {
					if (res.confirm) {
						this.$api.cancelTravelShareOrder(shareOrder.id).then(res => {
							uni.hideLoading()
							uni.showToast({
								title: '取消成功',
								icon: 'success'
							});
							this.loadOrderList()
						})
					}
				}
			})
			
		},
		// 分享代付订单
		openShareOrder(shareOrder) {
			if (shareOrder.share_image_url) {
				uni.previewImage({
					urls: [shareOrder.share_image_url]
				});
			} else {
				uni.previewImage({
					urls: [shareOrder.qrcode]
				});
			}
		},

		// 刷新订单状态
		refreshOrderStatus(orderId, newStatus) {
			const orderIndex = this.orderList.findIndex(order => order.id === orderId);
			if (orderIndex !== -1) {
				this.orderList[orderIndex].status = newStatus;
			}
		},

		// 下拉刷新
		onRefresh() {
			uni.showLoading({
				title: '刷新中...'
			});

			// 重新加载订单列表
			this.loadOrderList();
		},

		// 加载更多
		loadMore() {
			if (!this.hasMore || this.loading) return;

			this.loading = true;
			uni.showLoading({
				title: '加载中...'
			});

			// 计算下一页
			this.currentPage += 1;
			const params = {
				distributor_id: this.userInfo.id,
				pageNo: this.currentPage,
				pageSize: 10
			};

			this.$api.getTravelShareOrderList(params).then(res => {
				this.loading = false;
				uni.hideLoading();

				if (res && res.list && res.list.length > 0) {
					this.orderList = [...this.orderList, ...res.list];
					this.hasMore = this.orderList.length < res.total;
				} else {
					this.hasMore = false;
				}
			}).catch(error => {
				console.error('加载更多代付订单失败:', error);
			});
		},

		// 获取订单描述
		getOrderDesc(sku_spec) {
			if (!sku_spec) {
				return ''
			}
			let _sku_spec = JSON.parse(sku_spec)
			let desc = ''
			if (_sku_spec) {
				for (let key in _sku_spec) {
					desc += `${_sku_spec[key]} `
				}
			}
			return desc
		},

		// 格式化时间
		formatTime(timeStr) {
			if (!timeStr) return '';
			const date = new Date(timeStr);
			return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
		},

		// 初始化数据
		initData() {
			this.loading = true;
			uni.showLoading({
				title: '加载中...'
			});

			// 调用API获取订单列表
			this.loadOrderList();
		},

		// 加载代付订单列表
		loadOrderList() {
			// 重置页码
			this.currentPage = 1;

			const params = {
				distributor_id: this.userInfo.id,
				pageNo: this.currentPage,
				pageSize: 10
			};

			this.$api.getTravelShareOrderList(params).then(res => {
				this.loading = false;
				uni.hideLoading();

				if (res && res.list) {
					this.orderList = res.list;
					this.hasMore = this.orderList.length < res.total;
				}
			}).catch(error => {
				this.loading = false;
				console.error('获取代付订单列表失败:', error);
			});
		}
	},
	onLoad() {
		this.initData();
		// this.getSystemInfo();
	}
}
</script>

<style lang="scss">
.order-container {
	height: 100vh;
	overflow: hidden;
	display: flex;
	flex-direction: column;
	background-color: #f5f5f5;
}

// 顶部搜索栏
.header {
	//position: fixed;
	//top: 0;
	//left: 0;
	//right: 0;
	//z-index: 1000;
	background-color: #fff;
	//padding-right: 140rpx;

	padding:24rpx 32rpx;
	.header-content {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.search-container {
		flex: 1;
		display: flex;
		align-items: center;
		gap: 20rpx;
		margin-right: 20rpx;

		.search-box {
			flex: 1;
			display: flex;
			align-items: center;
			background-color: #f5f5f5;
			border-radius: 50rpx;
			padding: 0 24rpx;
			height: 72rpx;
			border: 2rpx solid #A6A6A6;
			position: relative;

			.search-icon {
				width: 32rpx;
				height: 32rpx;
				margin-right: 16rpx;
			}

			.search-input {
				flex: 1;
				font-size: 28rpx;
				color: #333;
			}

			.search-placeholder {
				color: #999;
			}
		}

		.search-btn {
			color: #333;

			.search-btn-text {
				font-size: 28rpx;
			}

			&:active {
				background-color: #555;
			}
		}
	}
}

// 分类标签
.category-tabs {
	flex-shrink: 0;
	display: flex;
	align-items: center;
	padding: 24rpx 32rpx;
	background-color: #fff;
	gap: 40rpx;
	border-bottom: 2rpx solid #f0f0f0;
	overflow-x: auto;

	.category-item {
		flex-shrink: 0;
		position: relative;
		padding-bottom: 16rpx;

		.category-text {
			font-size: 28rpx;
			color: #666;
			font-weight: 400;
		}

		&.active {
			.category-text {
				color: #333;
				font-weight: 500;
			}

			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 0;
				right: 0;
				height: 4rpx;
				background-color: #FFC300;
				border-radius: 2rpx;
			}
		}

		&:active {
			opacity: 0.7;
		}
	}
}

// 订单列表
.order-list {
	flex-grow: 1;
	padding-top: 24rpx;
	width: 100%;
	box-sizing: border-box;
	overflow: hidden;
	padding-bottom: 60rpx;
}

// 加载状态
.loading-state {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 120rpx 32rpx;

	.loading-text {
		font-size: 28rpx;
		color: #999;
	}
}

// 空状态
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 120rpx 32rpx;

	.empty-icon {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 32rpx;
		opacity: 0.6;
	}

	.empty-text {
		font-size: 32rpx;
		color: #999;
		margin-bottom: 16rpx;
	}

	.empty-desc {
		font-size: 26rpx;
		color: #ccc;
	}
}

.order-list-container {
	padding: 0 32rpx;
}

.order-item {
	background-color: #fff;
	border-radius: 16rpx;
	margin-bottom: 24rpx;
	overflow: hidden;
}

// 订单头部
.order-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 24rpx 32rpx;
	border-bottom: 1rpx solid #f0f0f0;

	.order-number {
		display: flex;
		align-items: center;
		gap: 12rpx;

		.order-number-text {
			font-size: 28rpx;
			color: #333;
			font-weight: 500;
		}

		.copy-btn {
			font-size: 24rpx;
			color: #333;
			padding: 4rpx 8rpx;
			border-radius: 4rpx;
			background-color: rgba(255, 107, 53, 0.1);

			&:active {
				background-color: rgba(255, 107, 53, 0.2);
			}
		}
	}

	.order-status {
		padding: 8rpx 16rpx;
		border-radius: 8rpx;
		font-size: 24rpx;

		&.status-pending-pricing {
			background-color: #e3f2fd;
			color: #2196f3;
		}

		&.status-pending {

			background-color: #ffebee;
			color: #f44336;
		}

		&.status-paid {
			background-color: #e8f5e8;
			color: #4caf50;
		}

		&.status-shipped {
			background-color: #e8f5e8;
			color: #4caf50;
		}

		&.status-pending-receipt {
			background-color: #fff8e1;
			color: #ff9800;
		}

		&.status-completed {
			background-color: #e8f5e8;
			color: #4caf50;
		}

		&.status-cancelled {
			background-color: #f5f5f5;
			color: #999;
		}

		&.status-refunding {
			background-color: #ffebee;
			color: #f44336;
		}

		&.status-refunded {
			background-color: #f5f5f5;
			color: #999;
		}

		.status-text {
			font-weight: 500;
		}
	}
}

// 商品信息
.order-product {
	display: flex;
	padding: 24rpx 32rpx;
	gap: 20rpx;

	.product-image {
		width: 120rpx;
		height: 120rpx;
		flex-shrink: 0;
	}

	.product-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 8rpx;

		.product-title {
			font-size: 28rpx;
			color: #333;
			font-weight: 500;
			line-height: 1.4;
		}

		.product-desc {
			font-size: 24rpx;
			color: #666;
		}

		.order-time {
			font-size: 22rpx;
			color: #999;
			margin-top: 4rpx;
		}
	}

	.product-price {
		display: flex;
		align-items: baseline;
		gap: 4rpx;

		.price-symbol {
			font-size: 24rpx;
			color: #333;
		}

		.price-value {
			font-size: 32rpx;
			color: #333;
			font-weight: 600;
		}
	}
}

// 代付金额信息
.prepay-info {
	display: flex;
	align-items: center;
	padding: 16rpx 32rpx;
	background-color: #f8f9fa;
	border-top: 1rpx solid #f0f0f0;

	.prepay-label {
		font-size: 26rpx;
		color: #666;
		margin-right: 8rpx;
	}

	.prepay-value {
		font-size: 26rpx;
		color: #ff6b35;
		font-weight: 500;
	}
}

// 操作按钮
.order-actions {
	display: flex;
	justify-content: flex-end;
	align-items: center;
	gap: 16rpx;
	padding: 24rpx 32rpx;
	border-top: 1rpx solid #f0f0f0;

	.action-btn {
		padding: 12rpx 24rpx;
		border-radius: 8rpx;
		font-size: 24rpx;
		font-weight: 500;

		&.primary {
			background-color: #FFC300;
			color: #333;

			&:active {
				background-color: #e55a2b;
			}
		}

		&.secondary {
			background-color: #f5f5f5;
			color: #666;

			&:active {
				background-color: #e8e8e8;
			}
		}

		.action-text {
			font-size: 26rpx;
		}
	}
}

// 加载更多
.load-more {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 80rpx;
	margin: 40rpx 0;

	.load-more-text {
		font-size: 28rpx;
		color: #666;
	}

	&:active {
		opacity: 0.7;
	}
}

.no-more {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 80rpx;
	margin: 40rpx 0;

	.no-more-text {
		font-size: 24rpx;
		color: #ccc;
	}
}
</style>
